import 'package:event_bus_plus/event_bus_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';

/// 描述: 路由管理
/// 
/// @Author tangzhentao
///  @CreatedTime 21:07 2022/6/17
/// 

/// 路由Key
final GlobalKey<NavigatorState> _navigatorKey = GlobalKey();
final EventBus _eventBus = EventBus();

class XfgNav {
  static GlobalKey<NavigatorState> get navigatorKey => _navigatorKey;
  static BuildContext get currentContext => _navigatorKey.currentContext!;
  static NavigatorState? get currentState => _navigatorKey.currentState;
  static EventBus get eventBus => _eventBus;

  static bool isFirst = true;

  static T read<T>() => XfgNav.currentContext.read<T>();

  static watch<T>() => XfgNav.currentContext.watch()<T>();

  static Future pushNamed<T extends Object?>(String route, {Object? arguments}) async {
    return _navigatorKey.currentState?.pushNamed(route, arguments: arguments);
  }

  static Future<T?> pushPage<T extends Object?>(Widget page) async {
    return await _navigatorKey.currentState?.push(CupertinoPageRoute(builder: (_) => page));
  }

  static Future<T?> pushReplacementPage<T extends Object?>(Widget page) async {
    return await _navigatorKey.currentState?.pushReplacement(CupertinoPageRoute(builder: (_) => page));
  }

  static Future<T?> pushReplacementNamed<T extends Object?>(String routeName, {Object? arguments}) async {
    return await _navigatorKey.currentState?.pushReplacementNamed(routeName, arguments: arguments);
  }

  // /// 打开内置web view页面
  // static Future<T?> pushWebPage<T extends Object?>({required String url, String? title, bool isWhite = false}) async {
  //   return await _navigatorKey.currentState?.push(CupertinoPageRoute(builder: (_) => WebViewPage(url: url, title: title, isWhite: isWhite)));
  // }

  static Future<T?> pushNamedAndRemoveUntil<T extends Object?>(String newRouteName, {String? routeName, Object? arguments}) async {
    return await _navigatorKey.currentState?.pushNamedAndRemoveUntil(newRouteName, (route) => route.settings.name == routeName, arguments: arguments);
  }

  static Future<T?> pushAndRemoveUntil<T extends Object?>(Widget newPage, {String? routeName, Object? arguments}) async {
    return await _navigatorKey.currentState?.pushAndRemoveUntil(CupertinoPageRoute(builder: (_) => newPage), (route) => route.settings.name == routeName);
  }

  static Future<T?> popAndPushNamed <T extends Object?, TO extends Object?>(String routeName, {TO? result, Object? arguments,}) async {
    return await _navigatorKey.currentState?.popAndPushNamed(routeName, result: result, arguments: arguments);
  }

  static bool canPop() {
    return _navigatorKey.currentState?.canPop() ?? false;
  }

  static void pop<T>([ T? result ]) {
    _navigatorKey.currentState?.pop(result);
  }

  static Future popUntil(String routeName) async {
    return _navigatorKey.currentState?.popUntil(ModalRoute.withName(routeName));
  }
}